﻿<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h3>WebSocketTest</h3>
    <div id="login">
        <div>
            <input id="serverIP" type="text" placeholder="服务器IP" value="127.0.0.1" autofocus="autofocus" />
            <input id="serverPort" type="text" placeholder="服务器端口" value="65531" />
            <input id="btnConnect" type="button" value="连接" onclick="connect()" />
        </div>
        <div>
            <input id="sendText" type="text" placeholder="发送文本" value="I'm WebSocket Client!" />
            <input id="btnSend" type="button" value="发送" onclick="send()" />
        </div>
        <div>
            <div>
                来自服务端的消息
            </div>
            <textarea id="txtContent" cols="50" rows="10" readonly="readonly"></textarea>
        </div>
    </div>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
    var socket;

    function connect() {
        var host = "ws://" + $("#serverIP").val() + ":" + $("#serverPort").val() + "/"
        socket = new WebSocket(host);
        try {

            socket.onopen = function (msg) {
                $("#btnConnect").disabled = true;
                alert("连接成功！");
            };

            socket.onmessage = function (msg) {
                if (typeof msg.data == "string") {
                    displayContent(msg.data);
                }
                else {
                    alert("非文本消息");
                }
            };

            socket.onclose = function (msg) { alert("socket closed!") };
        }
        catch (ex) {
            log(ex);
        }
    }
    function displayContent(msg) {
        $("#txtContent").val($("#txtContent").val()+"\r\n" +":  " + msg);
    }

    function send() {
        var msg = $("#sendText").val() + '\0'
        socket.send(msg);
    }
</script>